package com.hk.controller.admin;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import com.hk.model.dto.LoginDto;
import com.hk.model.pojo.Employee;
import com.hk.model.vo.CaptchaVO;
import com.hk.model.vo.LoginVO;
import com.hk.result.Result;
import com.hk.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "员工登录管理")
@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("员工登录")
    @PostMapping("/login")
    public LoginVO login(@RequestBody LoginDto loginDto) {
        LoginVO loginVO = employeeService.login(loginDto);
        return loginVO;
    }

    @ApiOperation("账号退出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    @ApiOperation("获取验证码")
    @GetMapping("/captchaImage")
    public CaptchaVO getCaptcha(String captchaId) {
        // 创建一个图像验证码宽度为130，高度为48，包含4个字符，干扰线10个
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 4, 10);
        // 获取验证码的文本
        String captchaText = circleCaptcha.getCode();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        circleCaptcha.write(outputStream);
        String img = Base64.encode(outputStream.toByteArray());

        // 如果没有传入captchaId，则生成一个随机字符串作为captchaId
        captchaId = Optional.ofNullable(captchaId).orElseGet(() -> UUID.randomUUID().toString());
        // 保存验证码文本到Redis中，有效期30秒
        stringRedisTemplate.opsForValue().set("captcha:" + captchaId, captchaText, 30, TimeUnit.SECONDS);


        CaptchaVO captchaVO = CaptchaVO.builder()
                .uuid(captchaId)
                .img(img).code(200)
                .msg("操作成功")
                .build();

        return captchaVO;
    }

}
